const sys = require(`./system.js`)
const title = '转卖权益'
const $ = sys.$(title)

sys.run($, 'task:all', (resList, cookie, index, username, password, item) => {
    return new Promise(async resolve => {
        // 查询转卖列表
        const minDay = 60
        const resp1 = await $.publicJS.canTransferList($, cookie, 1, 'deadLine-2')
        const zmList = resp1.data
            .filter(it => it.cardRate == null) // 过滤霸王卡权益
            .map(it => ({
                id: it.id,
                amount: it.amount,
                cardRate: it.cardRate,
                '剩余天数': parseInt((new Date(it.deadLine.substring(0, 10)) - new Date()) / 60 / 60 / 24 / 1000),
                '持有天数': parseInt((new Date() - new Date(it.buyDate)) / 60 / 60 / 24 / 1000)
        })).filter(it => it['剩余天数'] > minDay)

        if(!['15238540308'].includes(username)) {
            zmList.forEach(async it => {
                const bidResp = await $.publicJS.bidTransfer($, cookie, it.id)
                console.log(`账户 ${username} ${JSON.stringify(it)} ${JSON.stringify(bidResp)}`)
            })
        }
        const str = `账户 ${username}, 总可转 ${resp1.rows} 个, 需转 ${zmList.length} 个`
        console.log(str)
        resList.push(str)
        return resolve(resList)
    })
}, (resList) => {
    console.log('任务结束 resList:', resList)
    let userList = $.localStorage.get('task:userList', 'localStorageInfo') || []

    userList.push(...resList)
    const newUserList = $.publicJS.unique(userList, "id").map((it, idx) => ({
      index: idx,
      ...it,
    }))
    $.localStorage.set('task:userList', newUserList, 'localStorageInfo')
})
